<template>
  <div id="amap-container" class="amap-container"></div>
</template>

<script lang="js" setup name="MapDialog">
import {
  ComponentInternalInstance,
  getCurrentInstance,
  onMounted,
  ref,
  shallowRef,
  toRaw,
  defineEmits,
  nextTick
} from "vue";
import Taro, { eventCenter, useDidShow, useDidHide } from '@tarojs/taro'

import AMapLoader from "@amap/amap-jsapi-loader";
const MAP_KEY = "39cae8cb35cd12d8c605f324788e3040";
const MAP_CODE = "af5a7657629f4653a0e39888ed6c75e1";

const emits = defineEmits('mapSelectAddress');
// 地图实例对象
const AMapInstance = shallowRef(null);
const marker = shallowRef();
/**
 * 初始化地图
 * @return {Promise<void>}
 */
async function initMap() {
  try {
    if (AMapInstance.value !== null) {
      AMapInstance.value.clearMap();
    }
    await AMapLoader.load({
      key: MAP_KEY,
      // 安全密钥
      securityJsCode: MAP_CODE,
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.Autocomplete",
        "AMap.Geolocation",//定位
        "AMap.Geocoder",// 地址解析
        "AMap.Driving",//驾车规划
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
    AMapInstance.value = new AMap.Map("amap-container", {
      //设置地图容器id
      viewMode: "3D", //是否为3D地图模式
      zoom: 16, //初始化地图级别
      center: [87.630238, 43.859831], //初始化地图中心点位置
    });
    //绑定地图移动与缩放事件
    AMapInstance.value.on('dragging', logMapInfo);
    // 自己本身定位
    addMyAddressMarker()
  } catch (err) {
    console.warn(err);
  }


}
/**
 * 地图逆地理编码插件
 * @param LngLat
 */
function getAddress(LngLat) {
  const geoCoder = new AMap.Geocoder({
    city: '乌鲁木齐'
  });
  return new Promise((resolve, reject) => {
    geoCoder.getAddress(LngLat, (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        resolve(result);
      } else {
        reject(result);
      }
    });
  });
}
/**
 * 添加我的地址标记
 */
function addMyAddressMarker() {
  marker.value = new AMap.Marker(); // 创建标记对象
  marker.value.setPosition([87.630238, 43.859831]); // 设置标记位置
  AMapInstance.value.add(marker.value); // 将标记添加到地图实例中
  getAddress([87.630238, 43.859831]).then((res) => {
    mapAddress.value = res.regeocode.formattedAddress
    emits('mapSelectAddress', mapAddress.value)
    floatInfoWindow()
  })
}


//显示地图层级与中心点信息
function logMapInfo() {
  let zoom = AMapInstance.value.getZoom(); //获取当前地图级别
  let center = AMapInstance.value.getCenter(); //获取当前地图显示中心位置
  getAddress([center.lng, center.lat]).then((res) => {
    mapAddress.value = res.regeocode.formattedAddress
    emits('mapSelectAddress', mapAddress.value)
    floatInfoWindow(zoom)
  })
  // 添加一个浮标

};
const mapAddress = ref('当前位置')
function floatInfoWindow(zoom) {
  var content = [
    `<div style='display:flex;flex-flow:column;align-items:center;width:150px;height:120px;'>
    <div class='infoPao' style='min-width: 100px; min-height: 20px;border: 1px solid #000; background-color: #fff;text-align: center;padding: 2px;font-size:14px;border-radius: 10px;'>${mapAddress.value}</div>
    <div style='width:2px;height:30px;background-color:#000;'>
      </div>
      <div style='width:10px;height:10px;background-color:#ffb114;border-radius:50%;margin:0 auto;'><div>
      </div>
  `,
  ];
  var infoWindow = new AMap.InfoWindow({
    isCustom: true, //使用自定义窗体
    content: content.join("<br>"),
    offset: new AMap.Pixel(0, 0),
  });

  infoWindow.open(AMapInstance.value, AMapInstance.value.getCenter());
}

function toInitMap() {
  nextTick(() => {
    initMap();
  })
}
function DidMap() {
  if (AMapInstance.value) {
    AMapInstance.value.destroy();
    AMapInstance.value = null;
  }
}
defineExpose({ toInitMap, DidMap });
</script>
<style lang="scss" scoped>
@import "./MapComponents.scss";
</style>
